﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using DullBoard.Deserializers;
using DullBoard.Helper;
using DullBoard.Model;
using HtmlAgilityPack;

namespace DullBoard.Data
{
    internal class ForumRepository
    {
        public Forum GetForum(long forumId)
        {

            var forum = new Forum();

            var resourceFetcher = new WebResourceFetcher();
            var resource = resourceFetcher.Fetch(new Uri(String.Format("http://eu.battle.net/wow/en/forum/{0}/", forumId)));

            var stickyPosts = resource.DocumentNode.SelectNodes(XPathConst.ForumStickyPosts);
            if (stickyPosts != null)
                forum.Topics.AddRange(from x in stickyPosts select x.DeserializeTopic());
            
            forum.Topics.AddRange(from x in resource.DocumentNode.SelectNodes(XPathConst.ForumRegularPosts) select x.DeserializeTopic());

            return forum;
        }

        public List<Forum> GetForums()
        {
            //var resource = new HtmlDocument();
            //resource.Load("c:\\forumList.xml");

            var resourceFetcher = new WebResourceFetcher();
            var resource = resourceFetcher.Fetch(new Uri("http://eu.battle.net/wow/en/forum/"));

            var forums = resource.DocumentNode.SelectSingleNode("//div[@id=\"forum-list-interior\"]").DeserializeForums();
            return forums;
        }

        public Thread GetThread(long threadId)
        {
            var thread = new Thread();
            var resourceFetcher = new WebResourceFetcher();
            var resource = resourceFetcher.Fetch(new Uri(String.Format("http://eu.battle.net/wow/en/forum/topic/{0}", threadId)));

            //var resource = new HtmlDocument();
            //resource.Load("c:\\topicTemp.xml");

            thread.Posts.AddRange(from x in resource.DocumentNode.SelectNodes(XPathConst.TopicThreads) select x.DeserializePost());

            return thread;

        }
    }
}
